package com.bootdo.app.common.aop.weblog;

import com.alibaba.fastjson.JSON;
import com.bootdo.app.common.utils.ClientUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
  * @auther: Along
  * @description: web 请求日志切面拦截类
  */
@Aspect
@Component
public class WebLogAscept {
    
    private Logger logger = LoggerFactory.getLogger(WebLogAscept.class);

    /**
      * 设置切点
      */
    @Pointcut(value = "execution(* com.bootdo.app..controller..*.*(..))")
    public void logPointCut(){}


    /**
     * 前置通知
     */
    @Before(value = "logPointCut()")
    public void doBefore(JoinPoint joinPoint){
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        logger.info("HTTP-IP:{}", ClientUtil.getClientIp(request));
        logger.info("HTTP-URL:{}",request.getRequestURL());
        logger.info("HTTP-Method:{}",request.getMethod());
        logger.info("HTTP-Params:{}", Arrays.toString(joinPoint.getArgs()));
//        Enumeration<String> headerNames = request.getHeaderNames();
//        while(headerNames.hasMoreElements()){
//            String header = headerNames.nextElement();
//            logger.info("HTTP-HEADER---{}:{}",header,request.getHeader(header));
//        }
        logger.info("CLASS-Method:{}",joinPoint.getSignature().getDeclaringTypeName()+"."+joinPoint.getSignature().getName());
    }

    /**
      * 环绕通知
      */
    @Around(value = "logPointCut()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object obj = proceedingJoinPoint.proceed();
        logger.info("耗时:{}ms",System.currentTimeMillis()-startTime);
        return obj;
    }
    /**
     * 后置通知
     */
    @AfterReturning(returning = "result", pointcut = "logPointCut()")
    public void doAfter(Object result){
        logger.info("返回值 : " + JSON.toJSONString(result));
    }
}
